<script setup lang="ts">
import { ref, computed, onMounted } from "vue"
import BaseQuestion from "./base-question.vue"
import OptionItem from "./option-item.vue"
import nextLetter from "#/utils/nextLetter"
import { $t } from '@vben/locales';

defineOptions({ name: 'Checkbox' })

const props = defineProps<{
  modelValue: any
}>()

const optionsInit = [
  { name: 'A', content: '', file: '', path: '' },
  { name: 'B', content: '', file: '', path: '' },
  { name: 'C', content: '', file: '', path: '' },
  { name: 'D', content: '', file: '', path: '' },
]

const baseRef = ref()
const optionsEndIndex = computed(() => props.modelValue.options.length - 1)

const init = () => { }

onMounted(() => {
  // 确保数据类型正确
  if (!Array.isArray(props.modelValue.answers)) {
    props.modelValue.answers = []
  }
  // 只在选项为空时初始化，不要先清空
  if (!props.modelValue.options || props.modelValue.options.length === 0) {
    props.modelValue.options = [...optionsInit]
  }
})

const getData = async () => {
  return await baseRef.value?.getData()
}

const validate = () => {
  const baseValid = baseRef.value?.validate()
  const optionsValid = validateOptions()
  return baseValid && optionsValid
}

const addOption = () => {
  const options = props.modelValue.options
  let end = options[options.length - 1] || { name: '' }
  let letterNext = nextLetter(end.name ?? '')
  options.push({ name: letterNext, content: '', file: '', path: '' })
}

const del = (i: number) => {
  props.modelValue.options.splice(i, 1)
}

const handleUpload = (data: { file: any, item: any }) => {
  baseRef.value?.handleUpload({ file: data.file }, data.item)
}

const handleDeleteImage = (item: any) => {
  baseRef.value?.delImg(item)
}

// 选项组件引用数组
const optionRefs = ref<any[]>([])

// 验证所有选项
const validateOptions = () => {
  let isValid = true
  optionRefs.value.forEach(optionRef => {
    if (optionRef && !optionRef.validate()) {
      isValid = false
    }
  })
  return isValid
}

defineExpose({
  init,
  getData,
  validate
})
</script>

<template>
  <BaseQuestion ref="baseRef" :optionsInit="optionsInit" :multiple="true" :modelValue="modelValue">
    <template #options>
      <el-form-item :label="$t('questionBank.questionOptions')" prop="options">
        <div class="options-container">
          <!-- 选项网格布局，每行最多2个选项 -->
          <div class="options-grid">
            <div v-for="(item, i) in modelValue.options" :key="i" class="option-grid-item">
              <OptionItem :ref="(el: any) => { if (el) optionRefs[i] = el }" :model-value="modelValue.options[i]"
                @update:model-value="(newValue: any) => modelValue.options[i] = newValue"
                :show-delete="i >= 2 && i === optionsEndIndex" @upload="handleUpload"
                @delete-image="() => handleDeleteImage(modelValue.options[i])" @delete="() => del(i)" />
            </div>
          </div>

          <!-- 新增选项按钮 -->
          <div class="add-option-container">
            <el-button plain @click="addOption">{{ $t('questionBank.addOption') }}</el-button>
          </div>
        </div>
      </el-form-item>
    </template>
  </BaseQuestion>
</template>

<style scoped>
.options-container {
  width: 100%;
}

.options-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 16px;
  margin-bottom: 16px;
}

.option-grid-item {
  width: 100%;
}

.add-option-container {
  display: flex;
  /* justify-content: center; */
  margin-top: 16px;
}

/* 响应式设计 - 小屏幕下单列显示 */
@media (max-width: 768px) {
  .options-grid {
    grid-template-columns: 1fr;
  }
}
</style>
